<?php

function CreateThumb($name, $filename, $new_w, $new_h) {
    try {
        $system = explode(".", $name);
        if (preg_match("/jpg|jpeg/", strtolower($system[1]))) {
            $src_img = imagecreatefromjpeg($name);
        }
        if (preg_match("/png/", strtolower($system[1]))) {
            $src_img = imagecreatefrompng($name);
        }

        if (preg_match("/gif/", strtolower($system[1]))) {
            $src_img = imagecreatefromgif($name);
        }


        $old_x = imageSX($src_img);
        $old_y = imageSY($src_img);
        if ($old_x > $old_y) {
            $thumb_w = $new_w;
            $thumb_h = $old_y * ($new_h / $old_x);
        }
        if ($old_x < $old_y) {
            $thumb_w = $old_x * ($new_w / $old_y);
            $thumb_h = $new_h;
        }
        if ($old_x == $old_y) {
            $thumb_w = $new_w;
            $thumb_h = $new_h;
        }
        $dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
        imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);
        if (preg_match("/png/", $system[1])) {
            imagepng($dst_img, $filename);
        }
        elseif (preg_match("/gif/", $system[1])) {
            imagegif($dst_img, $filename);
        }
        else {
            imagejpeg($dst_img, $filename);
        }
        imagedestroy($dst_img);
        imagedestroy($src_img);
    }
    catch (Exception $e) {
        echo $name . " - " .  $e->getMessage();
    }
}

function endslash($str) {
    return rtrim($str, '/') . '/';
}

function extension($file) {
    $pos = strrpos($file, '.');
    if (!$pos)
        return '.???';
    $str = substr($file, $pos, strlen($file));
    return $str;
}

function lowertags($html) {
    $html = preg_replace("/(<\/?)(\w+)([^>]*>)/e", "'\\1'.strtolower('\\2').'\\3'", $html);
    $html = preg_replace(array('/<(br)>/', '/<(hr\s?.*?)>/', '/<(img\s.*?)>/'), '<\\1 />', stripslashes($html));
    return $html;
}

function vnstrips($text) {
    $text = str_replace("-", "", $text);
    $text = str_replace("  ", " ", $text);
    $text = str_replace(array(' ', '%', "/", "\\", '"', '?', '<', '>', "#", "^", "`", "'", "=", "!", ":", ",,", "..", "*", "&", "__", "▄", ",", "."), array('-', '', '', '', '', '', '', '', '', '', '', '', '-', '', '-', '', '', '', "_", "", "", "", "", ""), trim($text));

    $chars = array("a", "A", "e", "E", "o", "O", "u", "U", "i", "I", "d", "D", "y", "Y");
    $uni[0] = array("á", "à", "ạ", "ả", "ã", "â", "ấ", "ầ", "ậ", "ẩ", "ẫ", "ă", "ắ", "ằ", "ặ", "ẳ");
    $uni[1] = array("Á", "À", "Ạ", "Ả", "Ã", "Â", "Ấ", "Ầ", "Ậ", "Ẩ", "Ẫ", "Ă", "Ắ", "Ằ", "Ặ", "Ẳ");
    $uni[2] = array("é", "è", "ẹ", "ẻ", "ẽ", "ê", "ế", "ề", "ệ", "ể", "ễ");
    $uni[3] = array("É", "È", "Ẹ", "Ẻ", "Ẽ", "Ê", "Ế", "Ề", "Ệ", "Ể", "Ễ");
    $uni[4] = array("ó", "ò", "ọ", "ỏ", "õ", "ô", "ố", "ồ", "ộ", "ổ", "ỗ", "ơ", "ớ", "ờ", "ợ", "ở");
    $uni[5] = array("Ó", "Ò", "Ọ", "Ỏ", "Õ", "Ô", "Ố", "Ồ", "Ộ", "Ổ", "Ỗ", "Ơ", "Ớ", "Ờ", "Ợ", "Ở");
    $uni[6] = array("ú", "ù", "ụ", "ủ", "ũ", "ư", "ứ", "ừ", "ự", "ử", "ữ");
    $uni[7] = array("Ú", "Ù", "Ụ", "Ủ", "Ũ", "Ư", "Ứ", "Ừ", "Ự", "Ử", "Ữ");
    $uni[8] = array("í", "ì", "ị", "ỉ", "ĩ");
    $uni[9] = array("Í", "Ì", "Ị", "Ỉ", "Ĩ");
    $uni[10] = array("đ");
    $uni[11] = array("Đ");
    $uni[12] = array("ý", "ỳ", "ỵ", "ỷ", "ỹ");
    $uni[13] = array("Ý", "Ỳ", "Ỵ", "Ỷ", "Ỹ");
    for ($i = 0; $i <= 13; $i++)
        $text = str_replace($uni[$i], $chars[$i], $text);

    return strtolower($text);
}

function RssReader($link) {
    $doc = new DOMDocument();
    $doc->load($link);
    $arrFeeds = array();
    foreach ($doc->getElementsByTagName('item') as $node) {
        $itemRSS = array(
            'title' => trim($node->getElementsByTagName('title')->item(0)->nodeValue),
            'desc' => trim($node->getElementsByTagName('description')->item(0)->nodeValue),
            'link' => trim($node->getElementsByTagName('link')->item(0)->nodeValue),
            'date' => trim($node->getElementsByTagName('pubDate')->item(0)->nodeValue)
        );
        array_push($arrFeeds, $itemRSS);
    }

    return $arrFeeds;
}

function write($contents) {
    if ($GLOBALS['gzip']) {
        gzwrite($GLOBALS['fp'], $contents);
    }
    else {
        fwrite($GLOBALS['fp'], $contents);
    }
}

function read_file($file_name, $count = -1) {
    if ($count == -1) {
        $count = filesize($file_name);
    }
    $fp = fopen($file_name, "r");
    flock($fp, LOCK_SH);
    $ret = fread($fp, $count);
    flock($fp, LOCK_UN);
    fclose($fp);
    return $ret;
}

function xmail($from, $to, $subj, $text, $filename) {
    global $un;
    $fileContents = read_file($filename);
    $fileSize = strlen($fileContents);

    $file = base64_encode($fileContents);
    $file = chunk_split($file);

    if (!$file) {
        return FALSE;
    }
    else {
        for ($i = 0; $i < strlen($subj); $i++) {
            $subzh .= "=" . strtoupper(dechex(ord(substr($subj, $i, 1))));
        }
        $subj = "=?Windows-1251?Q?" . $subzh . '?=';
        $un = strtoupper(uniqid(time()));
        $head = "From: " . $from . "\n" .
                "X-Mailer: Black Angel\n" .
                "Reply-To: " . $from . "\n" .
                "Mime-Version: 1.0\n" .
                "Content-Type: multipart/mixed; boundary=\"----------" . $un . "\"\n\n";
        $zag = "------------" . $un . "\nContent-Type: text/plain; charset=utf-8\n" .
                "Content-Transfer-Encoding: 8bit\n\n" . $text . "\n\n" .
                "------------" . $un . "\n" .
                "Content-Type: application/octet-stream; name=\"" . basename($filename) . "\"\n" .
                "Content-Transfer-Encoding: base64\n" .
                "Content-Disposition: attachment; filename=\"" . basename($filename) . "\"\n\n";
        echo "<span id=mailPart." . basename($filename) . "></span><br>";


        $mailed = mail($to, $subj, $zag . $file, $head);


        if (!$mailed) {
            return FALSE;
        }
        else {
            return TRUE;
        }
    }
}

function download_image($inPath, $outPath) {
    $in = fopen($inPath, "rb");
    $out = fopen($outPath, "wb");
    while ($chunk = fread($in, 8192)) {
        fwrite($out, $chunk, 8192);
    }
    fclose($in);
    fclose($out);
}

function redirect($url = '', $time = 2) {   //hàm chuyển trang
    global $Template;
    if (empty($url)) {
        $url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'index.php';
    }

    $message = 'Xin vui lòng đợi 1 chút để chuyển về trang trước đó.<br>';

    $redirect = 1;
    $meta = '<meta http-equiv="Refresh" content="' . $time . '; URL=' . $url . '">';
    $Template->assign('message_redirect', ' ' . $message . 'Hoặc nhấn vào  <a class=orange href="' . $url . '">đây</a>  nếu quá ' . $time . ' giây mà trang chưa chuyển đi');
    $Template->assign('meta', $meta);
    return $redirect;
}

function show_message($message, $title='') {
    global $Template;
    if (trim($title) == NULL || empty($title)) {
        $title = "Thông báo";
    }
    $Template->assign('title', $title);
    $Template->assign('message', $message);
    $Template->display('message.html');
}

function Encode($string) {
    return htmlspecialchars(stripslashes($string), ENT_QUOTES);
}

function Decode($string) {
    return html_entity_decode($string, ENT_QUOTES);
}

function ArrayEncode($arr) {
    $i = 0;
    while ($arr[$i] != null) {
        $arr[$i] = Encode($arr[$i]);
        $i++;
    }
    return $arr;
}

function ArrayDecode($arr) {
    $i = 0;
    while ($arr[$i] != null) {
        $arr[$i] = Decode($arr[$i]);
        $i++;
    }
    return $arr;
}

function FileSizeURL($url) {
    $head = "";
    $status = "";
    $url_p = parse_url($url);
    $host = $url_p["host"];
    if (!preg_match("/[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*/", $host)) {
        // a domain name was given, not an IP
        $ip = gethostbyname($host);
        if (!preg_match("/[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*/", $ip)) {
            return -1;
        }
    }
    $port = @intval($url_p["port"]);
    if (!$port)
        $port = 80;
    $path = $url_p["path"];


    $fp = @fsockopen($host, $port, $errno, $errstr, 20);
    if (!$fp) {
        return false;
    }
    else {
        fputs($fp, "HEAD " . $url . " HTTP/1.1\r\n");
        fputs($fp, "HOST: " . $host . "\r\n");
        fputs($fp, "User-Agent: http://www.mydomain.com/my_application\r\n");
        fputs($fp, "Connection: close\r\n\r\n");
        $headers = "";
        while (!feof($fp)) {
            $headers .= fgets($fp, 128);
        }
    }
    fclose($fp);

    $return = -2;
    $arr_headers = explode("\n", $headers);

    foreach ($arr_headers as $header) {

        $s1 = "HTTP/1.1";
        $s2 = "Content-Length: ";
        $s3 = "Location: ";
        if (substr(strtolower($header), 0, strlen($s1)) == strtolower($s1))
            $status = substr($header, strlen($s1));
        if (substr(strtolower($header), 0, strlen($s2)) == strtolower($s2))
            $size = substr($header, strlen($s2));
        if (substr(strtolower($header), 0, strlen($s3)) == strtolower($s3))
            $newurl = substr($header, strlen($s3));
    }

    if (intval($size) > 0) {
        $return = intval($size);
    }
    else {
        $return = $status;
    }

    if (intval($status) == 302 && strlen($newurl) > 0) {
        $return = remote_file_size($newurl);
    }
    return intval($return / 1024);
}

/* function CheckLink($link)
  {
  $link = @parse_url($link);

  if (!$link) return false;

  $check_url =@fopen($link,"rb");
  if($check_url)
  return true;
  return false;
  } */

function CheckLink($url) {
    $url = @parse_url($url);

    if (!$url) {
        return false;
    }

    $url = array_map('trim', $url);
    $url['port'] = (!isset($url['port'])) ? 80 : (int) $url['port'];
    $path = (isset($url['path'])) ? $url['path'] : '';

    if ($path == '') {
        $path = '/';
    }

    $path .= ( isset($url['query'])) ? "?$url[query]" : '';

    if (isset($url['host']) AND $url['host'] != gethostbyname($url['host'])) {
        if (PHP_VERSION >= 5) {
            $headers = get_headers("$url[scheme]://$url[host]:$url[port]$path");
        }
        else {
            $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);

            if (!$fp) {
                return false;
            }
            fputs($fp, "HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n");
            $headers = fread($fp, 4096);
            fclose($fp);
        }
        $headers = (is_array($headers)) ? implode("\n", $headers) : $headers;
        return (bool) preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers);
    }
    return false;
}

function TextBetween($s1, $s2, $s) {
    $s1 = strtolower($s1);
    $s2 = strtolower($s2);
    $L1 = strlen($s1);
    $L2 = strlen($s2);
    $scheck = strtolower($s);

    $pos1 = strpos($scheck, $s1);
    if ($pos1 !== false) {
        $pos2 = strpos(substr($scheck, $pos1 + $L1), $s2);
        if ($pos2 !== false) {
            $mystr = substr($s, $pos1 + $L1, $pos2);
            $s = substr($s, $pos1 + $L1 + $pos2 + $L2);
            $scheck = strtolower($s);
        }
    }
    return trim($mystr);
}

function getFileName($strUrl) {
    $file = preg_split('%[/\\\\]%', $strUrl);

    return $file[sizeof($file) - 1];
}

function TextBetweenArray($s1, $s2, $s) {
    $myarray = array();
    $s1 = strtolower($s1);
    $s2 = strtolower($s2);
    $L1 = strlen($s1);
    $L2 = strlen($s2);
    $scheck = strtolower($s);

    do {
        $pos1 = strpos($scheck, $s1);
        if ($pos1 !== false) {
            $pos2 = strpos(substr($scheck, $pos1 + $L1), $s2);
            if ($pos2 !== false) {
                $myarray[] = substr($s, $pos1 + $L1, $pos2);
                $s = substr($s, $pos1 + $L1 + $pos2 + $L2);
                $scheck = strtolower($s);
            }
        }
    }
    while (($pos1 !== false) and ($pos2 !== false));

    return $myarray;
}

function FetchDataString($link) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $link);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $str = curl_exec($ch);
    curl_close($ch);
    return $str;
}

/* function FetchDataString($link)
  {
  $fp = fopen($link,"r");
  if (!$fp)
  echo "$errstr ($errno)<br />\n";
  else
  {
  while (!feof($fp))
  $document .= fgets($fp, 512);
  fclose($fp);
  }
  return $document;
  } */

function Unicode_Decode($entity) {
    $convmap = array(0x0, 0x10000, 0, 0xfffff);
    return mb_decode_numericentity($entity, $convmap, 'UTF-8');
}

function RemoveBetween($str1, $str2, $text) {
    $pos1 = strpos($text, $str1);
    $pos2 = strpos($text, $str2);


    return str_replace(substr($text, $pos1, $pos2 - $pos1 + strlen($str2)), '', $text);
}

function substr_ex($str1, $str2, $str) {
    $pos1 = strpos($str, $str1);
    $pos2 = strpos($str, $str2);

    if (is_numeric($str1))
        $pos1 = $str1;
    if (is_numeric($str2))
        $pos2 = $str2;

    return substr($str, $pos1, $pos2 - $pos1);
}

function IsImage($link) {
    if (@exif_imagetype($link))
        return 1;
    else
        return 0;
}

function getFileExt($filename) {
	$arr = explode('.',$filename);
    return $arr[sizeof($arr)-1];
}

?>